import router from './router'
import routes from '@/router/routes'
import Data from '@/utils/data'
const token = Data.getToken()
import getPageTitle from '@/utils/get-page-title'

// const whiteList = ['/login'] // no redirect whitelist
const whiteList = []
function vailteLogin(item) {
	if (!item.isLogin) {
		whiteList.push(item.path)
	}
	if (item.children && item.children.length > 0) {
		item.children.forEach(child => {
			vailteLogin(child)
		})
	}
}

routes.forEach(item => {
	// 是否需要登录，不需要登录的页面，加入白名单，未写isLogin的页面默认需要不需要登录
	vailteLogin(item)
})

// console.log(whiteList,'不校验登录的页面')

router.beforeEach(async (to, from, next) => {
	// set page title
	getPageTitle(to.meta.title)
	// determine whether the user has logged in
	const hasToken = token
	if (hasToken) {
		if (to.path === '/login') {
			// 如果已经登录，重定向到首页
			next({ path: '/' })
		}
		// 登录跳转其他的页面，通过
		else {
			next()
		}
	} else {
		if (whiteList.indexOf(to.path) !== -1) {
			next()
		} else {
			next(`/login?redirect=${to.path}`)
		}
	}
})

router.afterEach(() => {
	// finish progress bar
	// NProgress.done()
})
